package com.ruoyi.project.dict.spider.service.impl;

import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.CdnUtil;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.JsonUtil;
import com.ruoyi.common.utils.text.Convert;
import com.ruoyi.framework.aspectj.lang.annotation.DataSource;
import com.ruoyi.framework.aspectj.lang.enums.DataSourceType;
import com.ruoyi.framework.web.domain.Ztree;
import com.ruoyi.project.dict.material.domain.Material;
import com.ruoyi.project.dict.material.service.IMaterialService;
import com.ruoyi.project.dict.res.domain.MaterialRes;
import com.ruoyi.project.dict.res.service.IMaterialResService;
import com.ruoyi.project.dict.spider.domain.MaterialSpider;
import com.ruoyi.project.dict.spider.mapper.MaterialSpiderMapper;
import com.ruoyi.project.dict.spider.service.IMaterialSpiderService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 资料爬取Service业务层处理
 *
 * @author shixiangwen
 * @date 2020-05-12
 */
@Service
@DataSource(DataSourceType.DICT)
public class MaterialSpiderServiceImpl implements IMaterialSpiderService {

	protected static Log logger = LogFactory.getLog(MaterialSpiderServiceImpl.class);

	@Autowired
	private MaterialSpiderMapper materialSpiderMapper;

	@Autowired
	private IMaterialService materialService;

	@Autowired
	private IMaterialResService materialResService;

	/**
	 * 查询资料爬取
	 *
	 * @param id 资料爬取ID
	 * @return 资料爬取
	 */
	@Override
	public MaterialSpider selectMaterialSpiderById(Long id) {
		return materialSpiderMapper.selectMaterialSpiderById(id);
	}

	/**
	 * 查询资料爬取列表
	 *
	 * @param materialSpider 资料爬取
	 * @return 资料爬取
	 */
	@Override
	public List<MaterialSpider> selectMaterialSpiderList(MaterialSpider materialSpider) {
		List<MaterialSpider> list = materialSpiderMapper.selectMaterialSpiderList(materialSpider);
		list.forEach(item -> {
			item.setDownloadUrl(CdnUtil.getCdnAuthUrl(item.getDownloadUrl(), DateUtils.addMinutes(DateUtils.getNowDate(), 30)));
		});
		return list;
	}

	/**
	 * 新增资料爬取
	 *
	 * @param materialSpider 资料爬取
	 * @return 结果
	 */
	@Override
	public int insertMaterialSpider(MaterialSpider materialSpider) {
		return materialSpiderMapper.insertMaterialSpider(materialSpider);
	}

	/**
	 * 修改资料爬取
	 *
	 * @param materialSpider 资料爬取
	 * @return 结果
	 */
	@Override
	public int updateMaterialSpider(MaterialSpider materialSpider) {
		return materialSpiderMapper.updateMaterialSpider(materialSpider);
	}

	/**
	 * 删除资料爬取对象
	 *
	 * @param ids 需要删除的数据ID
	 * @return 结果
	 */
	@Override
	public int deleteMaterialSpiderByIds(String ids) {
		return materialSpiderMapper.deleteMaterialSpiderByIds(Convert.toStrArray(ids));
	}

	/**
	 * 删除资料爬取信息
	 *
	 * @param id 资料爬取ID
	 * @return 结果
	 */
	@Override
	public int deleteMaterialSpiderById(Long id) {
		return materialSpiderMapper.deleteMaterialSpiderById(id);
	}

	@Override
	public boolean updateSeq(Long pid, Long[] ids) {
		logger.info(pid);
		logger.info(JsonUtil.toJson(ids));
		MaterialSpider query = new MaterialSpider();
		query.setPid(pid);
		List<MaterialSpider> list = materialSpiderMapper.selectMaterialSpiderList(query);
		List<MaterialSpider> sortList = new ArrayList<>();
		boolean allHasSeq = true;
		Map<Long, MaterialSpider> map = new HashMap<>();
		for (MaterialSpider item : list) {
			map.put(item.getId(), item);
		}
		for (Long id : ids) {
			MaterialSpider item = map.get(id);
			if (item.getSeq() == 0) {
				allHasSeq = false;
			}
			sortList.add(item);
		}

		int seq = 1;

		if (allHasSeq && ids.length != list.size()) {
			seq = sortList.get(0).getSeq();
		}

		for (MaterialSpider spider : sortList) {
			spider.setSeq(seq++);
			materialSpiderMapper.updateMaterialSpider(spider);
		}

		return true;
	}

	private boolean isIn(Long[] ids, Long id) {
		for (Long i : ids) {
			if (id.equals(i)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 查询资料爬取树列表
	 *
	 * @return 所有资料爬取信息
	 */
	@Override
	public List<Ztree> selectMaterialSpiderTree() {
		MaterialSpider query = new MaterialSpider();
		query.setLeaf(0);
		List<MaterialSpider> materialSpiderList = materialSpiderMapper.selectMaterialSpiderList(query);
		List<Ztree> ztrees = new ArrayList<Ztree>();
		for (MaterialSpider materialSpider : materialSpiderList) {
			Ztree ztree = new Ztree();
			ztree.setId(materialSpider.getId());
			ztree.setpId(materialSpider.getPid());
			ztree.setName(materialSpider.getTitle());
			ztree.setTitle(materialSpider.getTitle());
			ztrees.add(ztree);
		}
		return ztrees;
	}

	@Override
	@Transactional(rollbackFor = { Exception.class })
	public boolean materialSave(Material material, Long[] ids) {

		material.setCreateTime(DateUtils.getNowDate());
		material.setTag(JsonUtil.toJson(material.getTags()));

		List<MaterialRes> materialResList = new ArrayList<>();
		long seq = 1L;
		for (long id : ids) {
			MaterialSpider materialSpider = materialSpiderMapper.selectMaterialSpiderById(id);

			if (materialSpider.getLeaf() == 0) {
				throw new BusinessException("只能导入内容数据，不能导入目录数据[" + materialSpider.getTitle() + "]");
			}

			MaterialRes materialRes = new MaterialRes();
			materialRes.setTitle(materialSpider.getTitle());
			materialRes.setSeq(seq++);
			materialRes.setContent(materialSpider.getContent());
			materialRes.setCreatedTime(DateUtils.getNowDate());
			materialRes.setResType(materialSpider.getResType());
			materialRes.setUrl(materialSpider.getDownloadUrl());
			materialRes.setSpiderId(id);
			materialResList.add(materialRes);

			materialSpider.setStatus(1);
			materialSpiderMapper.updateMaterialSpider(materialSpider);
		}

		materialService.add(material, materialResList);

		return true;
	}

	@Override
	@Transactional(rollbackFor = { Exception.class })
	public boolean materialSave(long materialId, Long[] ids) {

		List<MaterialRes> materialResList = new ArrayList<>();
		Integer seq = materialResService.selectMaxSeq(materialId);
		seq = seq == null ? 1 : seq + 1;
		for (long id : ids) {
			MaterialSpider materialSpider = materialSpiderMapper.selectMaterialSpiderById(id);

			if (materialSpider.getLeaf() == 0) {
				throw new BusinessException("只能导入内容数据，不能导入目录数据[" + materialSpider.getTitle() + "]");
			}

			MaterialRes materialRes = new MaterialRes();
			materialRes.setMaterialId(materialId);
			materialRes.setTitle(materialSpider.getTitle());
			materialRes.setSeq((long) seq++);
			materialRes.setContent(materialSpider.getContent());
			materialRes.setCreatedTime(DateUtils.getNowDate());
			materialRes.setResType(materialSpider.getResType());
			materialRes.setUrl(materialSpider.getDownloadUrl());
			materialRes.setSpiderId(id);
			materialResList.add(materialRes);

			materialSpider.setStatus(1);
			materialSpiderMapper.updateMaterialSpider(materialSpider);
		}

		materialResService.add(materialResList);

		return true;
	}
}
